import time
import psutil
from penguin.wechat import Wechat
# from penguin.email import SimpleEmail

class Monitor:
    def __init__(self):
        self.friend = None
        self.official_account = None
        self.wechat = Wechat()
        self.titles_need_remove:list[str] = [
            '省军区党委十四届十次全体（扩大）会议暨党管武装工作述职大会召开 郝鹏出席并讲话 孟凡清主持 王新伟出席',
            '全省深化安全生产治本攻坚三年行动暨省安委会一季度工作会议召开 李乐成出席并讲话',
            '省委常委会（扩大）会议暨省委理论学习中心组专题学习会召开 郝鹏主持并讲话 李乐成周波发言',
            '李乐成主持召开省政府常务会议'
        ]

    def check_keywords(self, keywords:list[str], titles:list[str])-> str | None:
        for title in titles:
            for keyword in keywords:
                if title.find(keyword) >= 0:
                    return title
        return None
    
    def remove_titles(self, titles:list[str])-> list[str]:
        new_titles:list[str] = []
        for title in titles:
            be_removed:bool = False
            for title_need_remove in self.titles_need_remove:
                if title == title_need_remove:
                    be_removed = True
            if not be_removed:
                new_titles.append(title)
        return new_titles

    def do(self, name:str, keywords:list[str]):
        if self.official_account == None:
            self.official_account = self.wechat.open_official_account(name)
            time.sleep(1)
        self.official_account.set_focus()
        titles = self.remove_titles(self.official_account.get_title_list())
        title = self.check_keywords(keywords, titles)
        if title != None:
            print('%s finished. found relative article %s .' % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), title))
            self.titles_need_remove.append(title)
            article = self.official_account.open_article(title)
            url = ''
            if article != None:
                url = article.get_url()
                article.close()
            self.wechat.set_focus()
            time.sleep(1)
            if self.friend == None:
                self.friend = self.wechat.open_friend('张靖宇')
            self.friend.send_message('新消息：' + url)
        else:
            print('%s finished. not found relative article.' % time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))


keywords = ['郝鹏','李乐成']
monitor = Monitor()

while True:
    try:
        monitor.do('辽宁日报', keywords)
    except Exception as e:
        print(e)
    time.sleep(3 * 60)